/**
 * Created by HYDN on 2020/6/19.
 */
const userDao=require('../dao/userDao');
const md5=require('../utils/md5/md5');

//1.注册，查询用户是否存在，不存在则增加
async function addUser(user){
    var ret=await userDao.findByName(user.name);
    if(ret.success){
        return{success:false,msg:'用户已存在'};
    }else {
        var data=await userDao.addUser(user);
        //在dao层做了数据处理，直接返回
        return data;
    }
}

//2.登录：找出用户，然后密码比对
//对数据库里的密码进行md5验证
async function login(user){
    var ret=await userDao.findByName(user.name);
    if(ret.success){
        var password=md5.toMd5(user.password);
        //console.log(ret);
        //console.log("pwd"+password+"---res.pwd:"+ret.user.password+"--:"+(password===ret.password));
        if(password===ret.user.password){
            return{success:true,user:ret.user};
        }else {
            return {success:false,msg:'用户密码不正确'};
        }
    }else {
        return {success:false,msg:'用户名不存在'};
    }
}

async function loginCookie(user){
    var ret=await userDao.findByName(user.name);
    //找到用户
    if(ret.success){
        if(user.password===ret.user.password){
            return{success:true,user:ret.user};
        }else {
            return {success:false,msg:'用户密码不正确'};
        }
    }else {
        return {success:false,msg:'用户名不存在'};
    }
}
exports.login=login;
exports.addUser=addUser;
exports.loginCookie=loginCookie;